package com.csii.oauth.filter.exchange.impl;
import com.csii.core.constant.CommonConstant;
import com.csii.core.system.vo.LoginUser;
import com.csii.core.util.TenantContext;
import com.csii.oauth.config.MocLoginUserProperties;
import com.csii.oauth.filter.exchange.IAuthExchange;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Description TODO
 * @Date 2020/9/16 13:13
 * @Created by Ian
 * @Contact: 19107614@qq.com
 */

@Slf4j
public class MocAuthExchange implements IAuthExchange {
	private MocLoginUserProperties mocLoginUser;
	public MocAuthExchange(MocLoginUserProperties mocLoginUser)
	{
		this.mocLoginUser=mocLoginUser;
	}

	@Override
	public void exchange(HttpServletRequest request, HttpServletResponse response) {
		LoginUser loginUser = new LoginUser();
		BeanUtils.copyProperties(mocLoginUser, loginUser);
		List<GrantedAuthority> authorityList = mocLoginUser.getAuthorities() == null ? AuthorityUtils.commaSeparatedStringToAuthorityList("login") : AuthorityUtils.createAuthorityList(mocLoginUser.getAuthorities());
		UsernamePasswordAuthenticationToken authenticationToken
				= new UsernamePasswordAuthenticationToken(
				loginUser, null, authorityList);
		//authenticationToken.setDetails(details);
		// 将对象传给安全上下文，对应的就会自动的进行权限判断，同时也可以获取到用户信息
		SecurityContextHolder.getContext().setAuthentication(authenticationToken);
		String tenantId = getTenantId(request);
		TenantContext.setTenant(tenantId);
	}

	private String getTenantId(HttpServletRequest request) {
		String tenantId = request.getHeader(CommonConstant.TENANT_ID);
		tenantId = tenantId == null ? request.getParameter(CommonConstant.TENANT_ID) : tenantId;
		return "0".equals(tenantId) ? null : tenantId;
	}
}
